package org.ruanjj.multithread.JUC;

import java.util.concurrent.locks.StampedLock;

public class StampedLockDemo {
    StampedLock lock = new StampedLock();
    private volatile int number = 0;
    public void read(){
        long stamp = lock.readLock();
        System.out.println(Thread.currentThread().getName() + "准备读取");
        try{
            for (int i = 0; i < 10; i++) {
                System.out.println(Thread.currentThread().getName() + "****"+i+"准备读取的值"+number);
            }
        }finally {
            lock.unlock(stamp);
        }
    }

    public void optimisticRead(){
        long stamp = lock.tryOptimisticRead();
        System.out.println(Thread.currentThread().getName() + "准备读取");

        for (int i = 0; i < 10; i++) {
            System.out.println(Thread.currentThread().getName() + "****"+i+"准备读取的值"+number);
        }

        if(!lock.validate(stamp)){
            try{
                stamp = lock.readLock();

                for (int i = 10; i < 20; i++) {
                    System.out.println(Thread.currentThread().getName() + "****"+i+"准备读取的值"+number);
                }
            }finally {
                lock.unlock(stamp);
            }



        }
    }

    public void write(){
        long stamp = lock.writeLock();
        try {
            Thread.sleep(5);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        System.out.println(Thread.currentThread().getName() + "准备修改");
        try{
            number++;
        }finally {
            lock.unlock(stamp);
        }
    }
}

class StampedLockTest{
    public static void main(String[] args) {
        StampedLockDemo s = new StampedLockDemo();

        new Thread(()->{
            s.read();
        }).start();

        new Thread(()->{
            s.write();
        }).start();

    }
}
